//
//
//  Created by longma on 2018/8/15.
//  Copyright © 2018年 XLH. All rights reserved.
//

#import "MJUITextField.h"


@implementation MJUITextField

- (void)awakeFromNib{
    [super awakeFromNib];
    
    self.tintColor = UIColor.mj_appColor;
    [self mj_setClearButtonWithImage:[UIImage imageNamed:@"icon_del"]];
    self.clearButtonMode = UITextFieldViewModeWhileEditing;
//    [self setMj_placeholderColor:[MJUIColorFromHex(0x3C3C43) colorWithAlphaComponent:0.6]];
    
}



-(void)layoutSubviews{
    [super layoutSubviews];
   
    //适配 placeholder 太长显示不全，不会自适应调节字体
    if(self.placeholder){
        [self.superview layoutIfNeeded];
        self.adjustsFontSizeToFitWidth = true;
        
        UIColor *placeholderColor = [MJUIColorFromHex(0x3C3C43) colorWithAlphaComponent:0.6];

        NSDictionary<NSAttributedStringKey, id> *placeholderAttributes = @{NSForegroundColorAttributeName: placeholderColor,NSFontAttributeName: self.font};
        NSMutableAttributedString *attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:self.placeholder attributes:placeholderAttributes];
        
        UITextField *textField = self;
        UIFont *placeholderFont = [UIFont systemFontOfSize:textField.font.pointSize];
        
        // 调整占位符字体大小以适应宽度
        CGFloat textWidth = [attributedPlaceholder size].width;
        while (textWidth > textField.bounds.size.width) {
            placeholderFont = [UIFont systemFontOfSize:placeholderFont.pointSize - 1];
    //        NSLog(@"MJLog=======placeholderFont================%lf",placeholderFont.pointSize);
            placeholderAttributes = @{NSFontAttributeName: placeholderFont, NSForegroundColorAttributeName: placeholderColor};
            [attributedPlaceholder setAttributes:placeholderAttributes range:NSMakeRange(0, self.placeholder.length)];
            textWidth = [attributedPlaceholder size].width;
        }
        
        //  设置placeholder字体
        self.attributedPlaceholder = attributedPlaceholder;
    }
   
}

@end
